package role

import (
	"context"
	"fast-boot/app/model"
	"gorm.io/gorm"

	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SetMenuIdsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 分配菜单权限给角色
func NewSetMenuIdsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SetMenuIdsLogic {
	return &SetMenuIdsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SetMenuIdsLogic) SetMenuIds(in *types.SysSetMenuIdsReq) (resp *types.SysRoleSucessResp, err error) {

	if err := l.svcCtx.GormClient.GormDb.Transaction(func(tx *gorm.DB) error {
		//删除
		if err := tx.Where("role_id = ?", in.RoleId).Delete(&model.SysRoleMenuModel{}).Error; err != nil {
			return err
		}
		for _, menuId := range in.MenuIds {
			if err := tx.FirstOrCreate(&model.SysRoleMenuModel{}, model.SysRoleMenuModel{
				RoleID: in.RoleId,
				MenuID: menuId,
			}).Error; err != nil {
				return err
			}
		}
		return nil
	}); err != nil {
		return nil, err
	}
	return &types.SysRoleSucessResp{}, nil
}
